package com.ld.oauth2.config.oauth.handle;


import com.ld.common.ResultInfoFactory;
import com.ld.emun.ErrorCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.session.InvalidSessionStrategy;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * sessoion失效后的处理逻辑
 *
 */
@Slf4j
public class CustomInvalidSessionHandle implements InvalidSessionStrategy {

    private SessionRegistry sessionRegistry;

    public void setSessionRegistry(SessionRegistry sessionRegistry) {
        this.sessionRegistry = sessionRegistry;
    }

    @Override
    public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        log.info("getSession().getId(): " + request.getSession().getId());
        log.info("getRequestedSessionId(): " + request.getRequestedSessionId());
        sessionRegistry.removeSessionInformation(request.getRequestedSessionId());

        cancelCookie(request,response);
        ResultInfoFactory result = new ResultInfoFactory();
        result.setMessage(ErrorCodeEnum.LOGIN_SESSION_INVALIDATE.getMessage());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(result.toJsonString(result));
    }

    private String getCookiePath(HttpServletRequest request) {
        String contextPath = request.getContextPath();
        return (contextPath.length() > 0) ? contextPath : "/";
    }

    protected void cancelCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie cookie = new Cookie("JSESSIONID", null);
        cookie.setMaxAge(0);
        cookie.setPath(getCookiePath(request));
        response.addCookie(cookie);
    }


}
